package org.fall.mvc.config;

import com.aliyuncs.ecs.model.v20140526.DescribePriceResponse;
import org.entity.Admin;
import org.entity.Role;
import org.fall.service.AdminService;
import org.fall.service.AuthService;
import org.fall.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.ServiceConfigurationError;
@Component
public class CrowdUserDetailsService implements UserDetailsService {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthService authService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //跟据账号查询admin对象
        Admin admin = adminService.getAdminByLoginAccts(s);
        //获取adminId
        Integer adminId = admin.getId();
        //跟据adminId查询角色信息
        List<Role> assignedRole = roleService.getAssignedRole(adminId);
        //跟据adminId查询权限信息
        List<String> assignedAuthNameByAdminId = authService.getAssignedAuthNameByAdminId(adminId);
        //创建集合对象来存储GrantedAuthority
        List<GrantedAuthority> authorities = new ArrayList<>();
        //遍历assignedRole存入角色信息
        for (Role role : assignedRole) {
            String roleName = "ROLE_" + role.getName();
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(roleName);
            authorities.add(simpleGrantedAuthority);
        }
        // 向List存放权限信息
        for (String authName : assignedAuthNameByAdminId){
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(authName);
            authorities.add(simpleGrantedAuthority);
        }
        //封装SecurityAdmin对象
        SecurityAdmin securityAdmin = new SecurityAdmin(admin, authorities);
        return securityAdmin;
    }
}
